<?php

namespace app\api\controller;

use think\Config;
use think\exception\HttpResponseException;
use think\exception\ValidateException;
use think\Lang;
use think\Request;
use think\Response;
use think\Route;
use think\Validate;
use app\api\dao\GoodsDao;
use think\cache\driver\Redis;
/**
 * API控制器基类
 */
class Api
{

    /**
     * @var Request Request 实例
     */
    protected $request;


    /**
     * 默认响应输出类型,支持json/xml
     * @var string
     */
    protected $responseType = 'json';
    /**
     * @var \app\api\model\User|array|mixed|\think\Model|null
     */

    public $userInfo;

    public $productInfo;

    public $appid;

    public $token;

    public $authAppid=[
        "5ra42ugg80", //优选驾考
    ];


    /**
     * 构造方法
     * @access public
     * @param Request $request Request 对象
     */
    public function __construct(Request $request = null)
    {
        $this->request = is_null($request) ? Request::instance() : $request;

        // 控制器初始化
        $this->_initialize();

    }

    /**
     * 初始化操作
     * @access protected
     */
    protected function _initialize()
    {
        $this->token =$this->request->header('token') ? $this->request->header('token') : $this->request->param('token');
        $this->appid =$this->request->header('appid') ? $this->request->header('appid') : $this->request->param('appid');
        $product_code =$this->request->header('product_code') ? $this->request->header('product_code') : $this->request->param('product_code');
        //需要验证登录
        if(!in_array($this->request->pathinfo(),$this->routerNoToken())){
            //校验登录
            if (empty($this->token) || empty($this->appid)){
                $this->error("您还未登录",null,10000);
            }
            if($product_code)
            {
                $this->productInfo=(new  GoodsDao)->detail($product_code);
            }
            $this->userInfo = json_decode($this->redis()->get("laravel_database_laravel_cache:".$this->appid.":".$this->token),1);
            if (empty($this->userInfo)) $this->error("身份验证失败",null,10001);
        }

        //不验证登录，需要获取用户信息
        if(in_array($this->appid,$this->authAppid))
        {
            $this->userInfo = json_decode($this->redis()->get("laravel_database_laravel_cache:".$this->appid.":".$this->token),1);
        }

    }


    public function routerNoToken(): array
    {
        //无需登录的接口
        return [
            'common/weather',
            'common/weather14',
            'common/air',
            'common/code',
            'common/festivalCate',
            'common/festivalToday',
            'common/festivalContent',
            'common/festivalContentDetail',
            'common/festivalContentImage',
            'common/festivalImage',
            'common/festivalImageContent',
            'common/festivalArticle',
            'common/festivalArticleDetail',
            'survey/product',
            'survey/notify',
            'survey/ztorder',
            'question/all',
            'question/list',
            'question/class',
            'question/chapter',
            'question/label',
            'question/group',
            'question/image',
        ];
    }

    public function redis(): Redis
    {
        $options=[
            "host"=>env("redis.host"),
            "port"=>env("redis.port"),
            "password"=>env("redis.password"),
            "select"=>env("redis.select"),
        ];

        return new Redis($options);
    }


    /**
     * 操作成功返回的数据
     * @param string $msg    提示信息
     * @param mixed  $data   要返回的数据
     * @param int $code   错误码，默认为1
     * @param string|null $type   输出类型
     * @param array  $header 发送的 Header 信息
     */
    protected function success($data = null, string $msg = '', int $code = 1, string $type = null, array $header = [])
    {
        $this->result($msg, $data, $code, $type, $header);
    }

    /**
     * 操作失败返回的数据
     * @param string $msg    提示信息
     * @param mixed  $data   要返回的数据
     * @param int $code   错误码，默认为0
     * @param string|null $type   输出类型
     * @param array  $header 发送的 Header 信息
     */
    protected function error(string $msg = '', $data = null, int $code = 0, string $type = null, array $header = [])
    {
        $this->result($msg, $data, $code, $type, $header);
    }

    /**
     * 返回封装后的 API 数据到客户端
     * @access protected
     * @param mixed  $msg    提示信息
     * @param mixed  $data   要返回的数据
     * @param int $code   错误码，默认为0
     * @param string|null $type   输出类型，支持json/xml/jsonp
     * @param array  $header 发送的 Header 信息
     * @return void
     * @throws HttpResponseException
     */
    protected function result($msg, $data = null, int $code = 0, string $type = null, array $header = [])
    {
        $result = [
            'code' => $code,
            'msg'  => $msg,
            'data' => $data,
            'time' => Request::instance()->server('REQUEST_TIME'),

        ];
        // 如果未设置类型则自动判断
        $type = $type ? $type : ($this->request->param(config('var_jsonp_handler')) ? 'jsonp' : $this->responseType);

        if (isset($header['statuscode'])) {
            $code = $header['statuscode'];
            unset($header['statuscode']);
        } else {
            //未设置状态码,根据code值判断
            $code = $code >= 1000 || $code < 200 ? 200 : $code;
        }
        $response = Response::create($result, $type, $code)->header($header);
        throw new HttpResponseException($response);
    }


    public function getRequest($url)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        // curl_setopt($curl, CURLOPT_TIMEOUT, 10);
        // curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 10);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        $output=json_decode($output,1);
        return $output;
    }







}
